//
//  MXMainViewController.swift
//  微博
//
//  Created by LoadingMx on 2017/3/16.
//  Copyright © 2017年 LoadingMx. All rights reserved.
//

import UIKit



class MXMainViewController: UITabBarController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupChildControllers()
        setComposeButton()
    }
    /// 控制设备的方向
    /** 
     landscape  : 横屏，风景画
     portrait   : 竖屏，肖像
     
     - 使用代码控制设备的方向,好处: 可以在需要横屏的时候,单独处理!
     - 设置支持的方向之后,当前的控制器及子控制器都会遵守这个方向!
     - 如果播放视频,通常通过 modal 展现的!
    */
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return .portrait
    }
    
    
    // MARK: - 私有控件
    /// 撰写按钮
    public lazy var composeButton: UIButton = UIButton.cz_imageButton("tabbar_compose_icon_add", backgroundImageName: "tabbar_compose_button")
    
    // MARK: - 监听方法
    // FIXME: - 没有实现
    // private 能够保证方法私有,仅在当前对象被访问
    
    @objc func composeStatus() {
        print("撰写微博")
        // 测试方向旋转
        let vc = UIViewController()
        vc.view.backgroundColor = UIColor.cz_random()
        let nav = UINavigationController(rootViewController: vc)
        present(nav, animated: true, completion: nil)
    }
    
}

extension MXMainViewController {
    
    /// 设置所有子控制器
    public func setupChildControllers() {
        
        // 0. 获取沙盒 json 路径
        let docDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        let jsonPath = (docDir as NSString).appendingPathComponent("main.json")
        
        // 加载 data
        var data = NSData(contentsOfFile: jsonPath)
        // 判断 data 是否有内容, 如果没有,说明本地沙盒没有文件
        if data == nil {
            // 从 bundle 加载配置的 json
            let path = Bundle.main.path(forResource: "main.json", ofType: nil)
            data = NSData(contentsOfFile: path!)
        }
        
        // 反序列化转换成数组
        guard let array = try? JSONSerialization.jsonObject(with: data! as Data, options: []) as? [[String : Any]]
        
        else {
            return
        }

        // 遍历数组, 循环创建控制器数据
        var arrayM = [UIViewController]()
        for dict in array! {
            arrayM.append(controller(dict: dict))
        }
        
        // 设置 TabBar 的子控制器
        viewControllers = arrayM

    }
    
    // 设置撰写按钮
    public func setComposeButton() {
        tabBar.addSubview(composeButton)
        // 计算按钮的宽度
        let count = CGFloat(childViewControllers.count)
        // 将向内的宽度减小,按钮的宽度就会变大,遮住容错点,防止穿帮!
        let w = tabBar.bounds.width / count - 1
        
        composeButton.frame = tabBar.bounds.insetBy(dx: 2 * w, dy: 0)
        
        // 按钮的监听方法
        
        composeButton.addTarget(self, action: #selector(composeStatus), for: .touchUpInside)
        
        
    }
    private func controller(dict: [String : Any]) -> UIViewController {
        // 1. 取得字典内容
        guard let clsName = dict["clsName"] as? String,
            let title = dict["title"] as? String,
            let imageName = dict["imageName"] as? String,
            let cls = NSClassFromString(Bundle.main.namespace + "." + clsName) as? MXBaseViewController.Type,
            let visitorDict = dict["visitorInfo"] as? [String : String]
            else {
                return UIViewController()
        }
        
        // 2. 创建视图控制器
        let vc = cls.init()
        vc.title = title
        
        // 设置访客信息字典
        vc.visitorInfoDicttionary = visitorDict
        
        // 3. 设置图片
        vc.tabBarItem.image = UIImage(named: "tabbar_" + imageName)
        vc.tabBarItem.selectedImage = UIImage(named: "tabbar_" + imageName + "_selected")?.withRenderingMode(.alwaysOriginal)
        // 4. 设置TabTar 标题字体 大小 和 颜色
        vc.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.orange], for: .highlighted)
        // 系统默认字体大小 12  注意: 设置字体大小要 normal 模式
        vc.tabBarItem.setTitleTextAttributes([NSFontAttributeName: UIFont.systemFont(ofSize: 12)], for: UIControlState.normal)
        let nav = MXNavigationController(rootViewController: vc)
        return nav
    }
    
    
}
